package org.meichao.interceptor;

import com.github.pagehelper.util.StringUtil;
import org.meichao.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Component
public class VerifyTokenInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(VerifyTokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //打印请求头
        printHead(request);
        String token = CommonUtils.getCurrentUserKey(request);
        if(StringUtil.isEmpty(token)){
            logger.error("token校验失败:{}", token);
            return false;
        }
        return true;
    }

    private static void printHead(HttpServletRequest request){
        Enumeration<String> enumeration = request.getHeaderNames();
        StringBuilder sb = new StringBuilder();
        while(enumeration.hasMoreElements()){
            String str = enumeration.nextElement();
            sb.append("[").append(str).append(":").append(request.getHeaders(str)).append("]\n");
        }
        logger.info("head:{}", sb);
    }
}
